<template>
  <div class="problems">
    <SideNav />
    <div class="main-content">
      <!-- 题库类型切换 -->
      <div class="library-tabs">
        <div 
          class="tab" 
          :class="{ active: activeTab === 'public' }"
          @click="activeTab = 'public'"
        >
          <i class="fas fa-globe"></i> 公共题库
        </div>
        <div 
          class="tab" 
          :class="{ active: activeTab === 'group' }"
          @click="activeTab = 'group'"
        >
          <i class="fas fa-users"></i> 小组题库
        </div>
      </div>

      <!-- 顶部筛选栏 -->
      <div class="filter-bar">
        <div class="search-box">
          <i class="fas fa-search"></i>
          <input type="text" placeholder="搜索题目..." v-model="searchQuery">
        </div>
        <div class="filter-options">
          <div class="filter-group">
            <label>难度</label>
            <select v-model="selectedDifficulty">
              <option value="">全部</option>
              <option value="EASY">简单</option>
              <option value="MEDIUM">中等</option>
              <option value="HARD">困难</option>
            </select>
          </div>
          <div class="filter-group">
            <label>状态</label>
            <select v-model="selectedStatus">
              <option value="">全部</option>
              <option value="solved">已解决</option>
              <option value="attempted">尝试过</option>
              <option value="unsolved">未开始</option>
            </select>
          </div>
          <div class="filter-group" v-if="activeTab === 'group'">
            <label>小组</label>
            <select v-model="selectedGroup">
              <option value="">全部小组</option>
              <option v-for="group in userGroups" :key="group.id" :value="group.id">
                {{group.name}}
              </option>
            </select>
          </div>
        </div>
        <!-- 上传题目按钮 -->
        <button class="upload-btn" @click="showUploadDialog">
          <i class="fas fa-plus"></i>
          上传题目
        </button>
      </div>

      <!-- 题目列表 -->
      <div class="problems-table">
        <table>
          <thead>
            <tr>
              <th class="status-col">状态</th>
              <th class="id-col">#</th>
              <th class="title-col">题目</th>
              <th class="difficulty-col">难度</th>
              <th class="acceptance-col">通过率</th>
              <th class="source-col" v-if="activeTab === 'group'">来源</th>
              <th class="status-col" v-if="isAdmin">审核状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="problem in filteredProblems" :key="problem.id" @click="goToProblem(problem.id)">
              <td class="status-col">
                <i :class="getStatusIcon(problem.status)" :title="problem.status"></i>
              </td>
              <td class="id-col">{{problem.id}}</td>
              <td class="title-col">{{problem.title}}</td>
              <td class="difficulty-col">
                <span :class="['difficulty-tag', problem.difficulty]">
                  {{getDifficultyText(problem.difficulty)}}
                </span>
              </td>
              <td class="acceptance-col">{{problem.acceptance}}%</td>
              <td class="source-col" v-if="activeTab === 'group'">{{problem.groupName}}</td>
              <td class="status-col" v-if="isAdmin">
                <span :class="['review-status', problem.reviewStatus]">
                  {{getReviewStatusText(problem.reviewStatus)}}
                </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页控件 -->
      <div class="pagination">
        <button :disabled="currentPage === 1" @click="changePage(currentPage - 1)">
          <i class="fas fa-chevron-left"></i>
        </button>
        <span class="page-info">第 {{currentPage}} 页</span>
        <button :disabled="isLastPage" @click="changePage(currentPage + 1)">
          <i class="fas fa-chevron-right"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import SideNav from '@/components/SideNav.vue'
import { baseURL } from '@/utils/api'
import axios from 'axios'

export default {
  name: 'ProblemsView',
  components: {
    SideNav
  },
  data() {
    return {
      activeTab: 'public',
      searchQuery: '',
      selectedDifficulty: '',
      selectedStatus: '',
      selectedGroup: '',
      currentPage: 1,
      problemsPerPage: 10,
      isAdmin: false, // 根据用户角色设置
      userGroups: [
        { id: 1, name: '算法学习小组' },
        { id: 2, name: '前端开发小组' }
      ],
      problems: [],
      totalProblems: 0,
      isLoading: false
    }
  },
  methods: {
    // 辅助函数：从Vue响应式对象中提取属性值
    extractProperty(obj, propName, defaultValue = null) {
      try {
        // 尝试直接访问
        if (obj[propName] !== undefined) {
          return obj[propName];
        }
        
        // 尝试通过getter访问
        if (typeof Object.getOwnPropertyDescriptor(obj, propName)?.get === 'function') {
          return Object.getOwnPropertyDescriptor(obj, propName).get.call(obj);
        }
        
        return defaultValue;
      } catch (e) {
        console.error(`提取属性 ${propName} 失败:`, e);
        return defaultValue;
      }
    },
    
    showUploadDialog() {
      this.$router.push('/problem/upload')
    },
    getStatusIcon(status) {
      const icons = {
        solved: 'fas fa-check-circle text-success',
        attempted: 'fas fa-clock text-warning',
        unsolved: 'far fa-circle text-muted'
      }
      return icons[status] || icons.unsolved
    },
    getDifficultyText(difficulty) {
      const texts = {
        EASY: '简单',
        MEDIUM: '中等',
        HARD: '困难'
      }
      return texts[difficulty] || ''
    },
    getReviewStatusText(status) {
      const texts = {
        REVIEWING: '待审核',
        PASS: '已通过',
        FAIL: '已拒绝'
      }
      return texts[status] || ''
    },
    goToProblem(id) {
      this.$router.push(`/problem/${id}`)
    },
    changePage(page) {
      this.currentPage = page
      this.fetchProblems()
    },
    async fetchProblems() {
      this.isLoading = true;
      try {
        // 构建查询参数
        const queryParams = new URLSearchParams({
          pageNum: this.currentPage.toString(),
          pageSize: this.problemsPerPage.toString()
        });

        let url;
        
        // 根据当前选择的标签页决定使用哪个API
        if (this.activeTab === 'group') {
          // 使用小组题库API
          url = `${baseURL}/CodeQuestion-service/problems/getGroupProblems`;
          
          // 添加user_id参数
          const userId = localStorage.getItem('userId');
          if (userId) {
            queryParams.append('user_id', userId);
          }
          
          // 如果选择了特定小组，添加group_id参数
          if (this.selectedGroup) {
            queryParams.append('group_id', this.selectedGroup);
            queryParams.append('show_single_group', 'true');
          } else {
            // 如果选择了"全部小组"
            queryParams.append('show_all_groups', 'true');
            
            // 检查用户是否有小组
            if (this.userGroups.length === 0) {
              console.error('用户没有加入任何小组');
              this.isLoading = false;
              setTimeout(() => {
                alert('您尚未加入任何小组，请先创建或加入小组');
                // 切换回公共题库
                this.activeTab = 'public';
              }, 100);
              return; // 直接返回，不继续请求
            }
          }
          
          // 添加一个标志，表示这是小组题库请求
          queryParams.append('is_group', 'true');
        } else {
          // 使用公共题库API
          url = `${baseURL}/CodeQuestion-service/problems/searchFullProblems`;
          queryParams.append('type', 'PUBLIC');
        }
        
        // 构建完整的API URL
        const fullUrl = `${url}?${queryParams.toString()}`;
        
        console.log('请求题目列表URL:', fullUrl);
        
        // 使用axios发送请求
        const response = await axios.get(fullUrl);
        const data = response.data;
        
        if (data.result === 'success') {
          console.log('获取题目列表成功:', data);
          
          // 直接使用返回的problemList
          this.problems = data.problemList || [];
          this.totalProblems = data.total || this.problems.length;
          
          // 简单处理一下数据，添加必要的默认值
          this.problems = this.problems.map(problem => {
            // 检查是否有必要的字段，如果没有则设置默认值
            return {
              ...problem,
              // 添加必要的默认值
              id: problem.id || 0,
              title: problem.title || '未命名题目',
              status: problem.status === 1 ? 'solved' : 'unsolved',
              acceptance: problem.acceptanceRate || 0,
              difficulty: problem.difficulty || 'MEDIUM',
              // 根据当前标签页设置类型
              type: this.activeTab === 'group' ? 'GROUP' : 'PUBLIC',
              // 设置小组名称 - 优先使用从数据库返回的groupName
              groupName: problem.groupName || problem.group_name || (this.activeTab === 'group' ? 
                (this.selectedGroup ? this.userGroups.find(g => g.id == this.selectedGroup)?.name || '小组题库' : '全部小组') 
                : '公共题库'),
              // 确保group_id有值，如果是小组题库但group_id为null，则设置为-1以便能够显示
              group_id: this.activeTab === 'group' && problem.group_id === null ? 
                        (this.selectedGroup || -1) : (problem.group_id || -1),
              // 设置审核状态
              reviewStatus: problem.review_status || 'REVIEWING'
            };
          });
          
          console.log('处理后的题目列表:', this.problems);
        } else {
          throw new Error(data.message || '获取题目失败');
        }
      } catch (error) {
        console.error('获取题目列表失败:', error);
        // 显示错误消息
        alert('获取题目列表失败: ' + (error.response?.data?.message || error.message));
      } finally {
        this.isLoading = false;
      }
    },
    // 获取用户所在的小组
    async fetchUserGroups() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) return Promise.resolve();
        
        // 获取我创建的小组
        const createdResponse = await axios.get(`${baseURL}/CodeQuestion-service/groups/my-created/${userId}`);
        
        // 获取我加入的小组
        const joinedResponse = await axios.get(`${baseURL}/CodeQuestion-service/groups/my-joined/${userId}`);
        
        console.log('获取小组列表响应:', { created: createdResponse.data, joined: joinedResponse.data });
        
        if (createdResponse.data.result === 'success' && joinedResponse.data.result === 'success') {
          // 合并小组列表并标记角色
          const createdGroups = createdResponse.data.groups.map(group => ({
            id: group.id,
            name: group.name,
            role: 'admin'
          }));
          
          const joinedGroups = joinedResponse.data.groups.map(group => ({
            id: group.id,
            name: group.name,
            role: 'member'
          }));
          
          // 创建一个Map用于去重，优先保留管理员角色
          const groupMap = new Map();
          
          // 先添加管理员角色的小组
          createdGroups.forEach(group => {
            groupMap.set(group.id, group);
          });
          
          // 再添加成员角色的小组，但不覆盖已有的管理员角色
          joinedGroups.forEach(group => {
            if (!groupMap.has(group.id)) {
              groupMap.set(group.id, group);
            }
          });
          
          // 转换回数组
          this.userGroups = Array.from(groupMap.values());
          console.log('处理后的用户小组列表:', this.userGroups);
        } else {
          console.error('获取小组列表失败:', createdResponse.data.message, joinedResponse.data.message);
          this.userGroups = [];
        }
        
        return Promise.resolve();
      } catch (error) {
        console.error('获取用户小组列表失败:', error);
        this.userGroups = [];
        return Promise.resolve();
      }
    }
  },
  computed: {
    filteredProblems() {
      // 首先检查problems是否为空
      if (!this.problems || this.problems.length === 0) {
        return [];
      }
      
      return this.problems.filter(problem => {
        // 基本筛选条件
        const matchesSearch = problem.title && problem.title.toLowerCase().includes(this.searchQuery.toLowerCase());
        const matchesDifficulty = !this.selectedDifficulty || problem.difficulty === this.selectedDifficulty;
        const matchesStatus = !this.selectedStatus || problem.status === this.selectedStatus;
        
        // 处理小组筛选
        let matchesGroup = true;
        if (this.activeTab === 'group' && this.selectedGroup) {
          // 尝试获取group_id，可能有不同的字段名
          const groupId = problem.group_id !== undefined ? problem.group_id : 
                         (problem.groupId !== undefined ? problem.groupId : null);
          
          // 如果在小组题库中但没有选择特定小组，或者group_id匹配选择的小组，则显示
          matchesGroup = groupId === parseInt(this.selectedGroup) || 
                        (this.activeTab === 'group' && !this.selectedGroup);
        }
        
        // 调试输出
        if (this.activeTab === 'group' && !matchesGroup) {
          console.log('题目不匹配小组筛选:', problem.title, '小组ID:', problem.group_id);
        }
        
        return matchesSearch && matchesDifficulty && matchesStatus && matchesGroup;
      });
    },
    isLastPage() {
      return this.currentPage * this.problemsPerPage >= this.totalProblems;
    },
    totalPages() {
      return Math.ceil(this.totalProblems / this.problemsPerPage);
    }
  },
  created() {
    // 先获取用户所在的小组，然后再获取题目列表
    this.fetchUserGroups().then(() => {
      // 获取题目列表
      this.fetchProblems();
    });
    
    // 检查用户是否是管理员
    const userRole = localStorage.getItem('userRole');
    this.isAdmin = userRole === 'ADMIN';
  },
  watch: {
    // 监听标签页切换，重新获取数据
    async activeTab() {
      this.currentPage = 1; // 重置页码
      
      // 如果切换到小组题库，确保已获取到小组信息
      if (this.activeTab === 'group' && this.userGroups.length === 0) {
        await this.fetchUserGroups();
      }
      
      this.fetchProblems();
    },
    // 监听小组选择变化，重新获取数据
    selectedGroup() {
      this.currentPage = 1; // 重置页码
      if (this.activeTab === 'group') {
        this.fetchProblems();
      }
    }
  }
}
</script>

<style scoped>
.problems {
  min-height: 100vh;
  background: #f0f7ff;
}

.main-content {
  margin-left: 60px;
  padding: 20px;
}

/* 筛选栏样式 */
.filter-bar {
  background: white;
  padding: 16px;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
  display: flex;
  gap: 20px;
  align-items: center;
}

.search-box {
  flex: 1;
  position: relative;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #5b7b9a;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  font-size: 14px;
}

.filter-options {
  display: flex;
  gap: 16px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  color: #5b7b9a;
  font-size: 14px;
}

.filter-group select {
  padding: 8px 24px 8px 12px;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  color: #2c3e50;
  background: white;
}

/* 题目列表样式 */
.problems-table {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 16px;
  text-align: left;
  border-bottom: 1px solid #e8f4ff;
}

th {
  background: #f8faff;
  color: #5b7b9a;
  font-weight: 500;
}

tr:hover {
  background: #f8faff;
  cursor: pointer;
}

.status-col {
  width: 60px;
  text-align: center;
}

.id-col {
  width: 80px;
}

.difficulty-col {
  width: 100px;
}

.acceptance-col {
  width: 100px;
}

.difficulty-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.difficulty-tag.EASY {
  background: #e8f6f1;
  color: #42b983;
}

.difficulty-tag.MEDIUM {
  background: #fdf6ec;
  color: #e6a23c;
}

.difficulty-tag.HARD {
  background: #fef0f0;
  color: #f56c6c;
}

.tag {
  display: inline-block;
  padding: 2px 8px;
  margin: 2px;
  background: #e8f4ff;
  color: #3498db;
  border-radius: 4px;
  font-size: 12px;
}

/* 分页控件样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 20px;
}

.pagination button {
  padding: 8px 16px;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  background: white;
  color: #3498db;
  cursor: pointer;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination .page-info {
  color: #5b7b9a;
}

/* 状态图标颜色 */
.text-success {
  color: #42b983;
}

.text-warning {
  color: #e6a23c;
}

.text-muted {
  color: #909399;
}

.library-tabs {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.tab {
  padding: 12px 24px;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  color: #5b7b9a;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.tab.active {
  background: #3498db;
  color: white;
}

.upload-btn {
  padding: 8px 16px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.upload-btn:hover {
  background: #3aa876;
}

.review-status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.review-status.REVIEWING {
  background: #fdf6ec;
  color: #e6a23c;
}

.review-status.PASS {
  background: #e8f6f1;
  color: #42b983;
}

.review-status.FAIL {
  background: #fef0f0;
  color: #f56c6c;
}

.source-col {
  width: 150px;
}
</style> 